package com.weijianhuawen.wjblog.admin.event.subscriber;

import com.weijianhuawen.wjblog.admin.event.UpdatePersonMessageEvent;
import com.weijianhuawen.wjblog.common.domain.dos.CommentDo;
import com.weijianhuawen.wjblog.common.domain.dos.UserDetailDo;
import com.weijianhuawen.wjblog.common.domain.mapper.CommentMapper;
import com.weijianhuawen.wjblog.common.domain.mapper.UserDetailMapper;
import com.weijianhuawen.wjblog.common.domain.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description:
 * @date: 2024-12-23 23:30
 */

@Component
@Slf4j
public class UpdatePersonMessageSuscriber implements ApplicationListener<UpdatePersonMessageEvent> {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserDetailMapper userDetailMapper;
    @Override
    @Async("threadPoolTaskExecutor")
    public void onApplicationEvent(UpdatePersonMessageEvent event) {
        // 获取用户id
        Long userId = event.getUserId();
        // 获取当前线程名称
        String threadName = Thread.currentThread().getName();

        log.info("【修改个人资料事件订阅者】 处理任务线程名：{}", threadName);
        log.info("【修改个人资料事件订阅者】 开始消费事件！, 用户UID：{}!", userId);

        // 查询用户资料
        UserDetailDo userDetailDo = userDetailMapper.selectUserDetailByUserId(userId);

        if (Objects.isNull(userDetailDo)) {
            log.warn("【修改个人资料事件订阅者】 用户id为{}的资料已不存在！", userId);
            return;
        }

        // 获取相关发布评论
        List<CommentDo> commentDos = commentMapper.selectCommentListByUserId(userId);
        if (CollectionUtils.isEmpty(commentDos)) {
            log.warn("【修改个人资料事件订阅者】 用户id为{}的账户下，无发表评论或评论已全部被删除！", userId);
            return;
        }
        String avatar = userDetailDo.getAvatar();
        String nickname = userDetailDo.getNickname();
        // 遍历所有评论
        commentDos.forEach(commentDo -> {
            // 修改评论需展示的用户头像与昵称
            commentDo.setAvatar(avatar);
            commentDo.setNickname(nickname);
            // 修改
            commentMapper.updateById(commentDo);
        });
        log.warn("【修改个人资料事件订阅者】 事件处理完成！ 处理内容： 修改评论显示信息！");
    }
}
